var url = 'ws://183.129.184.70:9519/u_id=123';

var websocket = {
    debug: false,
    ws: null,          // websocket 对象
    url: url,
    lock: false,       // 锁定避免多次重连
    timeout: 5000,    // 超时时间19秒
    checkTimer: null,  // 检测计时器
    create: function (options) {
        try {
            this.ws = new WebSocket(this.url);
            // 绑定事件
            this.initEventHandle(options);
        } catch (error) {
            console.error(error)
        }
    },

    // 断线重连
    reconnect: function (options) {
        if (this.lock) return;
        if (this.debug) console.log('[websocket] 正在重连');
        // 重置计时器
        clearTimeout(this.checkTimer);
        this.lock = true;
        // 设置重连间隔
        setTimeout(() => {
            this.create(options);
            this.lock = false;
        }, 2000);

    },

    // 发送消息
    send: function (msg) {
        if (this.debug) console.log('>>>发送消息', msg);
        this.ws.send(JSON.stringify(msg));
        this.resetCheck();
    },

    // 初始化事件
    initEventHandle: function (options) {
        this.ws.onopen = () => {
            if (this.debug) console.log('[websocket] 已开启');
            this.resetCheck();
            typeof options.onopen == 'function' && options.onopen();
        }
        this.ws.onmessage = (evt) => {
            var msg = evt.data;
            // console.log(msg)
            if (msg.charAt(0) === '{' || msg.charAt(0) === '[') {
                msg = JSON.parse(msg)
            }
            if (this.debug) console.log('<<<收到消息', msg);
            this.resetCheck();
            typeof options.onmessage == 'function' && options.onmessage(msg);
        }
        this.ws.onclose = (err) => {
            if (this.debug) console.log('[websocket] 已关闭', err);
            this.reconnect(options);
            typeof options.onclose == 'function' && options.onclose();
        };
        this.ws.onerror = (err) => {
            if (this.debug) console.log('[websocket] 遇到错误', err);
            this.reconnect(options);
        };
    },

    // 检测是否断开链接
    resetCheck: function () {
        clearTimeout(this.checkTimer);
        this.checkTimer = setTimeout(() => {
            if (this.debug) console.log('[websocket] 服务器无响应');
            this.ws.close();
        }, this.timeout)
    }
}

export default websocket





